/**
 * $Revision: 1.0 $
 * $Author: Eric Yang $
 * $Date: Mar 1, 2010 11:20:51 PM $
 *
 * Author: Eric Yang
 * Date  : Mar 1, 2010 11:20:51 PM
 *
 */
package com.gooex.service.schedual.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.c4j.db.hibernate.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.gooex.domain.base.Order;
import com.gooex.domain.base.emun.OrderStatus;
import com.gooex.service.base.IOrderManager;
import com.gooex.service.schedual.ISchedualService;


/**
 * @author Eric Yang
 * @version 1.0
 */
public class UpdateOrderStatusServiceImpl implements ISchedualService {
	private static final Log logger = LogFactory.getLog(UpdateOrderStatusServiceImpl.class);

	private SessionFactory sessionFactory;

	private IOrderManager orderManager;

	/**
	 * 每天02:30执行. <br>
	 * 依次执行VOTING,QUOTING,INVITING状态的订单，顺序不能调换
	 */
	public void start() {
		try {
			Session session = HibernateUtil.openSession(sessionFactory);
			logger.info("Start schedual[" + this.getClass().getName() + "] at" + new Date());
			changeOrdersStatus(session, OrderStatus.VOTING);
			changeOrdersStatus(session, OrderStatus.QUOTING);
			changeOrdersStatus(session, OrderStatus.INVITING);
			logger.info("End schedual[" + this.getClass().getName() + "] at" + new Date());
		} catch (Exception e) {
			logger.error(e);
		} finally {
			HibernateUtil.closeSession(sessionFactory);
		}
	}

	private void changeOrdersStatus(Session session, OrderStatus status) {
		List<Order> orders = orderManager.getOrders(status, null);
		if (orders != null && orders.size() > 0) {
			for (Order order : orders) {
				try {
					logger
							.debug("Try to change status of the " + status.toString() + " order[" + order.getId()
									+ "] !");
					orderManager.changeOrderStatus(order);
				} catch (Exception e) {
					logger.debug("Change order[" + order.getId() + "] status exception:" + e.getMessage());
				}
			}
			session.flush();
		}
	}

	public void setOrderManager(IOrderManager orderManager) {
		this.orderManager = orderManager;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

}
